package servlet;

import java.io.*;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import util.*;
import bll.*;
import model.*;
import dal.*;

/**
 * Servlet implementation class CompanyServlet
 */
@WebServlet(urlPatterns = { "/Service", "/service", "/ServiceServlet", "/serviceServlet" }, initParams = {
        @WebInitParam(name = "mode", value = "") })
public class ServiceServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public ServiceServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/xml; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("new")) {

			if (RightUtil.<ServiceModel>checkInsertRight()) {

				// TODO : MORE CODE HERE

                getServletContext().getRequestDispatcher("/serviceNew.jsp").forward(request, response);
			} else {
				// TODO no right
			}
		} else if (mode.equalsIgnoreCase("edit")) {

                ServiceModel query = new ServiceModel();				
                String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));


				GenericDal<ServiceModel, ServiceModelExt> dal = new GenericDal<ServiceModel, ServiceModelExt>(
						new ServiceModel());

				ServiceModel obj = null;
				try {
					obj = dal.select(query);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (obj != null) {

					// TODO : MORE CODE HERE

                    request.setAttribute("service", obj);
                    getServletContext().getRequestDispatcher("/serviceEdit.jsp").forward(request, response);

				} else {
					// TODO : data not found
				}			
		} else if (mode.equalsIgnoreCase("view")) {
			
                ServiceModel query = new ServiceModel();				
                String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));


				GenericDal<ServiceModel, ServiceModelExt> dal = new GenericDal<ServiceModel, ServiceModelExt>(
						new ServiceModel());

				ServiceModel obj = null;
				try {
					obj = dal.select(query);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (obj != null) {
					// TODO : LOAD MASTER DATA HERE
					// It's specific code that cannot be generated

                    request.setAttribute("service", obj);
                    getServletContext().getRequestDispatcher("/serviceView.jsp").forward(request, response);

				} else {
					// TODO : data not found
				}			
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			ServiceModel obj = new ServiceModel();
			
			// TODO set name here

			GenericDal<ServiceModel, ServiceModelExt> dal = new GenericDal<ServiceModel, ServiceModelExt>(new ServiceModel());

			int res = 0;
			try {
				String txtName = request.getParameter("name");
				obj.setName(txtName);
				res = dal.insert(obj);
				PrintWriter out = response.getWriter();
				//TODO: check failed inserting case
				if (res > 0)
				{
					String resultXML = createXML("" + res);
					out.println(resultXML);
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("insert")) {
			
				ServiceModel obj = new ServiceModel();

                String name = request.getParameter("name");
					obj.setName(name);

String status = request.getParameter("status");
                    if (status != null && !status.isEmpty()) {
					    obj.setStatus(Integer.parseInt(status));
                    }

String notification = request.getParameter("notification");
                    if (notification != null && !notification.isEmpty()) {
					    obj.setNotification(Integer.parseInt(notification));
                    }



				

                obj.setCreator(SessionUtil.getCurrentUserID());

				if (CommonBll.checkInputs(obj)) {
					GenericDal<ServiceModel, ServiceModelExt> dal = new GenericDal<ServiceModel, ServiceModelExt>(
							new ServiceModel());

					int res = 0;
					try {
						res = dal.insert(obj);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (res > 0) {
						// TODO : success, redirect to somewhere
					} else {
						// TODO : processing error here
					}
				} else {

					// invalid input

                    request.setAttribute("service", obj);
                    getServletContext().getRequestDispatcher("/serviceInput.jsp").forward(request, response);

				}		
		} else if (mode.equalsIgnoreCase("update")) {		

                ServiceModel query = new ServiceModel();				
                String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));


				GenericDal<ServiceModel, ServiceModelExt> dal = new GenericDal<ServiceModel, ServiceModelExt>(
						new ServiceModel());

				ServiceModel obj = null;
				try {
					obj = dal.select(query);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (obj != null) {

                    String name = request.getParameter("name");
					obj.setName(name);


					String status = request.getParameter("status");
					obj.setStatus(Integer.parseInt(status));


					String notification = request.getParameter("notification");
					obj.setNotification(Integer.parseInt(notification));



				

                    if (CommonBll.checkInputs(obj)) {	

					    int res = Integer.MIN_VALUE;
					    try {
						    res = dal.update(obj);
					    } catch (SQLException e) {
						    // TODO Auto-generated catch block
						    e.printStackTrace();
					    } catch (ClassNotFoundException e) {
						    // TODO Auto-generated catch block
						    e.printStackTrace();
					    } catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					    if (res == 0) {
						    // TODO success
					    } else {
						    // TODO error
					    }
                    } else {
					request.setAttribute("service", obj);
					getServletContext().getRequestDispatcher("/serviceEdit.jsp").forward(request, response);
				    }
				} else {
					// TODO data not found
				}			
		} else if (mode.equalsIgnoreCase("delete")) {		

                ServiceModel query = new ServiceModel();				
                String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));


				GenericDal<ServiceModel, ServiceModelExt> dal = new GenericDal<ServiceModel, ServiceModelExt>(
						new ServiceModel());

				int res = Integer.MIN_VALUE;
				try {
					res = dal.delete(query);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (res == 0) {
					// TODO success
				} else {
					// TODO fail
				}			
		}
	}
	protected String createXML(String _id) {
		try {

			DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
			Document doc = docBuilder.newDocument();
			Element service = doc.createElement("service");
			doc.appendChild(service);
			Element e_id = doc.createElement("id");
			service.appendChild(e_id);
			Text t_id = doc.createTextNode(_id);
			e_id.appendChild(t_id);

			TransformerFactory transfac = TransformerFactory.newInstance();
			Transformer trans = transfac.newTransformer();
			trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
			trans.setOutputProperty(OutputKeys.INDENT, "yes");

			// create string from xml tree
			StringWriter sw = new StringWriter();
			StreamResult result = new StreamResult(sw);
			DOMSource source = new DOMSource(doc);
			trans.transform(source, result);
			String xmlString = sw.toString();

			return xmlString;

		} catch (Exception e) {
			return "error";
		}
	}	

}